﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WindowsClientListener.AzureQueueService;

namespace ClientListner
{
  class Program
  {
    public static string myDeviceID = "2001";
    public static HelperServiceClient client = new HelperServiceClient();
    static void Main(string[] args)
    {
      client.CreateQueue("responsequeue");
      while (true)
      {
        try
        {
          string xmlMessage = client.GetMessage(myDeviceID, "requestqueue", true);
          if (xmlMessage == "") Console.WriteLine("No new messages");
          else
          {
            client.SendMessage("1", "responsequeue", ProcessMessage(xmlMessage));
          }
          System.Threading.Thread.Sleep(1000);
        }
        catch (Exception ex)
        {
          Console.WriteLine(ex.Message);
        }
      }
    }

    private static string ProcessMessage(string xmlMessage)
    {
      Console.WriteLine("Trying to execute command: " + xmlMessage);
      return ExecuteCommandSync(xmlMessage);
    }

    /// <summary>
    /// Executes a shell command synchronously.
    /// </summary>
    /// <param name="command">string command</param>
    /// <returns>string, as output of the command.</returns>
    private static string ExecuteCommandSync(object command)
    {
      string result = String.Empty;
      try
      {
        System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
        procStartInfo.RedirectStandardOutput = true;
        procStartInfo.UseShellExecute = false;
        // Do not create the black window.
        procStartInfo.CreateNoWindow = true;
        System.Diagnostics.Process proc = new System.Diagnostics.Process();
        proc.StartInfo = procStartInfo;
        proc.Start();
        // Get the output into a string
        result = proc.StandardOutput.ReadToEnd();
        // Display the command output.
        Console.WriteLine(result);
      }
      catch (Exception e)
      {
        result = e.Message;
      }
      return result;
    }
  }
}
